# -*- coding: utf-8 -*-

import json
import datetime
import logging

from django.utils.decorators import method_decorator
from django.views.generic import TemplateView

from common.lottery import METIS_GAME_TYPE
from common.platform.metis import db as metis_db
from common.utils.api import token_required
from common.utils.currency import convert_fen_to_yuan
from common.utils.decorator import response_wrapper
from common.utils.export import redirect_to_file, gen_filename
from common.utils.tz import utc_to_local_str
from common.utils.exceptions import ParamError
from common.utils import tz

_LOGGER = logging.getLogger(__name__)


class MetisOrderView(TemplateView):

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def get(self, req):
        query_dct = req.GET.dict()
        export = query_dct.pop('$export', None)
        if 'create_time' not in query_dct and 'user_id' not in query_dct:
            today = tz.local_now().strftime('%Y-%m-%d')
            query_dct['create_time'] = '{"$gte":"' + today + \
                                      ' 00:00:00","$lt":"' + today + ' 23:59:59"}'
        elif 'user_id' not in query_dct:
            create_time = eval(query_dct['create_time'])
            start_date = datetime.datetime.strptime(create_time['$gte'][0:10], "%Y-%m-%d")
            end_date = datetime.datetime.strptime(create_time['$lte'][0:10], "%Y-%m-%d")
            if 7 < (end_date - start_date).days:
                raise ParamError(u'时间区间大于7天')

        if export:
            filename = gen_filename('pay')
            header = ['ticket_id', 'user_id', 'game_id', 'play_type', 'round_id', 'bet_amount', 'bet_result',
                      'create_time']
            cn_header = [u'订单ID', u'用户ID', u'游戏类别', u'玩法', u'局号', u'押注金额', u'返还金额', u'购买时间']
        items, total_count, total_bet, total_win = metis_db.list_all_orders(query_dct)
        resp = []
        for item in items:
            data = item.as_dict()
            data.pop('extend')
            data.pop('created_at')
            data.pop('updated_at')
            data['bet_amount'] = convert_fen_to_yuan(item.bet_amount)
            data['bet_result'] = convert_fen_to_yuan(item.bet_result)
            # 返回金额(bet_win) = 下注金额(bet_amount) + 盈亏金额(bet_result)
            data['bet_win'] = data['bet_amount'] + data['bet_result']
            data['create_time'] = utc_to_local_str(item.create_time)
            row = []
            if export:
                for x in header:
                    if x == 'game_id' and data.get(x):
                        row.append(METIS_GAME_TYPE.to_dict()[data.get(x)])
                    else:
                        row.append(data.get(x, '-'))
                resp.append(row)
            else:
                resp.append(data)

        if export:
            return redirect_to_file(resp, cn_header, filename)

        return {'list': resp, 'page': query_dct.get('$page', 1),
                'total_count': total_count, 'size': len(resp),
                'total_bet': convert_fen_to_yuan(total_bet),
                'total_win': convert_fen_to_yuan(total_win)}


class MetisGameView(TemplateView):

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def get(self, req):
        query_dct = req.GET.dict()
        game_id = query_dct['game_id']
        items, total_count = metis_db.list_metis_game(query_dct, game_id)
        resp_items = []
        for item in items:
            data = item.as_dict()
            extend = json.loads(item.extend)
            data.pop('created_at')
            data.pop('updated_at')
            data['win_list'] = extend.get('section_bet_rate')
            data['create_time'] = utc_to_local_str(item.create_time)
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'total_count': total_count, 'size': len(resp_items)}


class MetisGamePartView(TemplateView):

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def get(self, req):
        query_dct = req.GET.dict()
        game_id = query_dct['game_id']
        items, total_count, total_bet, total_win = metis_db.list_metis_game_part(query_dct, game_id)
        resp_items = []
        for item in items:
            data = item.as_dict()
            data.pop('created_at')
            data.pop('updated_at')
            extend = json.loads(item.extend)
            data['win_area'] = extend.get('total_bet_result')
            data['bet_amount'] = convert_fen_to_yuan(item.bet_amount)
            data['bet_result'] = convert_fen_to_yuan(item.bet_result)
            data['create_time'] = utc_to_local_str(item.create_time)
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'total_count': total_count, 'size': len(resp_items),
                'total_bet': convert_fen_to_yuan(total_bet),
                'total_win': convert_fen_to_yuan(total_win)}
